package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;


public class PMProjectDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Label lblprojectName;
	@UiField Button btnViewProjectPlan;
	@UiField Button btnPMUpdateProjectStep2;
	@UiField Label lblStartDate;
	@UiField Label lblFinishDate;
	@UiField Label lblProjectName;
	@UiField Label lblInvestor;
	@UiField Label lblLocation;
	@UiField TextArea taDescription;
	@UiField Label lblProjectCode;
	@UiField Label lblInfo;
	@UiField ListBox cboStatus;
	@UiField SimplePager pager;
	@UiField Button btnSubCTList;
	@UiField(provided = true) CellTable<ProjectTaskDTO> ctbProjectWork = new CellTable<ProjectTaskDTO>();
	@UiField Button btnPJStaff;
	@UiField Button button;
	@UiField Button button_1;
	@UiField ListBox cboParentTask;
	@UiField ListBox cboTaskType;
	@UiField Button btnHmReq;
	@UiField Label labelFinshedDate;
	@UiField Label lblCom;
	//_________________________Common varius___________________________________
	

	private ProjectDTO currentProject = new ProjectDTO();
	CommonFuntion common = new CommonFuntion();
	private List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();

	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	final MultiSelectionModel<ProjectTaskDTO> selectionModel = new MultiSelectionModel<ProjectTaskDTO>();
	
	interface Binder extends UiBinder<Widget, PMProjectDetail> {
	}

	//END_________________________Common varius________________________________
	
	//___________________________Contructor____________________________________
	

 
	public PMProjectDetail() {
		initWidget(binder.createAndBindUi(this));
	}

	
	
	public PMProjectDetail(String projectId) {
		this();
		currentProject.setProjectID(projectId);
		getProjectInfo(projectId);
		
		
		projectService.getListTask(projectId, new AsyncCallback<List<ProjectTaskDTO>>() {
					
					@Override
					public void onSuccess(List<ProjectTaskDTO> result) {
						// TODO Auto-generated method stub
						listTask = result;
						loadForCbo();
						   int newTask = 0;
						   int currTask =0;
						   int finishTask =0;
						   int cancel =0;
						List<ProjectTaskDTO> listData = new ArrayList<ProjectTaskDTO>();
						for(ProjectTaskDTO task :listTask)
						{
							//if(task.getSubTasks()!=null&&!task.getSubTasks().equals(""))
						//	{
								if(task.getStatus()==1)
								{
									listData.add(task);
									currTask++;
								}
								if(task.getStatus()==0)
								{
									newTask++;
								}
								if(task.getStatus()==2)
								{
									finishTask++;
								}
								if(task.getStatus()==3)
								{
									cancel++;
								}
							//}
						}
						initTable();
						lblInfo.setText("Tổng số công việc : "+ listTask.size()+"  | Đang tiến hành : "+currTask + "  | Chưa bắt đầu : "+ newTask +" |  Hoàn thành : "+finishTask+" | Ngừng thực hiện :" +cancel);
						LoadDataForTable(listData);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("không thể load dữ liệu");
					}
				});
		
		
	}
	
	
	//End___________________________Contructor____________________________________
	

	//______________________________Common function_______________________________
	
	public void loadForCbo()
	{
		cboStatus.addItem("Tất cả","-1");
		cboStatus.addItem("Chưa bắt đầu","0");
		cboStatus.addItem("Ðang tiến hành","1");
		cboStatus.addItem("Ðã hoàn thành","2");
		cboStatus.addItem("Ngừng thực hiện","3");
		cboStatus.setSelectedIndex(2);
		
		cboTaskType.addItem("Tất cả","0");
		cboTaskType.addItem("Công việc gốc","1");
		cboTaskType.addItem("Mốc mục tiêu","2");
		cboTaskType.addItem("Công việc cha","3");
		cboTaskType.addItem("Công việc con","4");
		
		cboParentTask.addItem("Tất cả","-1");
		cboParentTask.addItem("Không có công việc cha","0");
		for(ProjectTaskDTO task : listTask)
		{
			if(task.getGroup()==1)
			{
				cboParentTask.addItem(task.getTaskName(),task.getId());
			}
			
		}
	}

	 @SuppressWarnings("unchecked")
	public void initTable()
	 {
		 ctbProjectWork.setSelectionModel(selectionModel,
				    DefaultSelectionEventManager.<ProjectTaskDTO> createCheckboxManager());
				Column<ProjectTaskDTO, Boolean> checkColumn = new Column<ProjectTaskDTO, Boolean>(
				    new CheckboxCell(true, false)) {
				  @Override
				  public Boolean getValue(ProjectTaskDTO object) {
				    // Get the value from the selection model.
				    return selectionModel.isSelected(object);
				  }
				};
	
            
			TextColumn<ProjectTaskDTO> startDate = new TextColumn<ProjectTaskDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(ProjectTaskDTO task) {
					Date startDate = new Date(task.getStartDate());
					return startDate.getDate() + "/" + (startDate.getMonth() + 1)
							+ "/" + (startDate.getYear() + 1900);
				}
			};
			TextColumn<ProjectTaskDTO> finishDate = new TextColumn<ProjectTaskDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(ProjectTaskDTO task) {
					
					if(task.getFinishDate()==null)
					{
						return "__";
					}
					Date finishDate = new Date(task.getFinishDate());
					
					return finishDate.getDate() + "/" + (finishDate.getMonth() + 1) + "/"
							+ (finishDate.getYear() + 1900);
				}
			};
			TextColumn<ProjectTaskDTO> dueDate = new TextColumn<ProjectTaskDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(ProjectTaskDTO task) {
					Date dueDate = new Date();
					
						  dueDate = new Date(task.getDueDate());
					
					return dueDate.getDate() + "/" + (dueDate.getMonth() + 1) + "/"
							+ (dueDate.getYear() + 1900);
				}
			};
			
			TextColumn<ProjectTaskDTO> stt = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					return task.getSTT()+"";
				}
			};
			TextColumn<ProjectTaskDTO> amountOfWork = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					
					return task.getAmountOfWork()+ " "+task.getUnit();
				}
			};
			TextColumn<ProjectTaskDTO> finishWork = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					Double data = task.getFinishedWork()*100;
				    Double data2 = 0d+data.intValue();
			
					return (data2/100)+ " "+task.getUnit();
				}
			};
			TextColumn<ProjectTaskDTO> weight = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					return task.getWeight().toString()+" %";
				}
			};


			
			TextColumn<ProjectTaskDTO> complete = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					Double comp = task.getFinishedWork()*10000/task.getAmountOfWork();
					Double comp2= comp.intValue()+0d;
					return comp2/100+" %";
				}
			};
		
			Column<ProjectTaskDTO, String> taskNameColumn = new Column<ProjectTaskDTO, String>(
					new ClickableTextCell()) {
				@Override
				public String getValue(ProjectTaskDTO object) {
					return object.getTaskName();
				}
			};
			taskNameColumn.setFieldUpdater(new FieldUpdater<ProjectTaskDTO, String>() {

				@Override
				public void update(int index, ProjectTaskDTO task, String value) {
					PMEntrypoint.get().PMTaskDetail(task);
				}

			});
			TextColumn<ProjectTaskDTO> taskType = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					if(task.getParentId()==0)
					{
						return "Công việc gốc";
					}
					if(task.getIsMile()==1)
					{
						return "Mốc mục tiêu";
					}
					if(task.getGroup()==1)
					{
						return "Công việc cha";
					}
					if(task.getSubTasks().equals("")||task.getSubTasks()==null)
					{
						return "Công việc con";
					}
					return task.getOptAccountName().toString();
				}
			};
			
			TextColumn<ProjectTaskDTO> status = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					if(task.getStatus()==0)
					{
						return"Chưa bắt đầu";
					}
					if(task.getStatus()==1)
					{
						return"Đang tiến hành";
					}
					if(task.getStatus()==2)
					{
						return"Đã hoàn thành";
					}
					if(task.getStatus()==3)
					{
						return"Ngừng thực hiện";
					}
					return"";
				}
			};
		
			taskNameColumn.setCellStyleNames("celltable");
			
			ctbProjectWork.setStyleName("ttable");
			ctbProjectWork.addColumn(stt, "STT");
			ctbProjectWork.setColumnWidth(stt, 6, Unit.PCT);
			ctbProjectWork.addColumn(taskNameColumn, "Tên công việc");
			ctbProjectWork.setColumnWidth(taskNameColumn, 23, Unit.PCT);
			ctbProjectWork.addColumn(amountOfWork, "Khối lượng");
			ctbProjectWork.setColumnWidth(amountOfWork, 9, Unit.PCT);
			//ctbProjectWork.addColumn(finishWork,"Hoàn thành");
			//ctbProjectWork.setColumnWidth(finishWork, 10, Unit.PCT);
			ctbProjectWork.addColumn(complete,"Hoàn thành(%)");
			ctbProjectWork.setColumnWidth(complete, 9, Unit.PCT);
			ctbProjectWork.addColumn(weight,"Trọng số(%)");
			ctbProjectWork.setColumnWidth(weight, 7, Unit.PCT);
			//ctbProjectWork.addColumn(weight,"Trọng số");
			//ctbProjectWork.addColumn(resource,"Người thực hiện");
			ctbProjectWork.addColumn(startDate, "Ngày bắt đầu");
			ctbProjectWork.setColumnWidth(startDate, 6, Unit.PCT);
			ctbProjectWork.addColumn(dueDate, "KT dự kiến");
			ctbProjectWork.setColumnWidth(dueDate, 6, Unit.PCT);
			ctbProjectWork.addColumn(finishDate, "KT Thực tế");
		
			finishDate.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
			ctbProjectWork.setColumnWidth(finishDate, 6, Unit.PCT);
			ctbProjectWork.addColumn(taskType,"Loại công việc");
			ctbProjectWork.setColumnWidth(taskType, 9, Unit.PCT);
			ctbProjectWork.addColumn(status,"Tình trạng");
			
			//ctbProjectWork.setColumnWidth(status, 16, Unit.PCT);
			//ctbTaskList.addColumn(deleteColumn, "");

	 }
	
		public void LoadDataForTable(List<ProjectTaskDTO> taskList) {
			ListDataProvider<ProjectTaskDTO> dataProvider = new ListDataProvider<ProjectTaskDTO>();
          try {
			// Connect the table to the data provider.
			dataProvider.addDataDisplay(ctbProjectWork);
			pager.setDisplay(ctbProjectWork);
			pager.setPageSize(5);
			List<ProjectTaskDTO> list = dataProvider.getList();
			int count =1;
			for (ProjectTaskDTO task : taskList) {
				task.setSTT(count+"");
				list.add(task);
				count++;
			}
          }catch(Exception ex){Window.alert(ex.getMessage());}
		}
		
	 private void displayProject() {
		 lblCom.setText(currentProject.getComplete()+" (%)");
		 if(currentProject.getStatus()==2||currentProject.getStatus()==3)
		 {
			 labelFinshedDate.setText(CommonFuntion.convertToDate(new Date(currentProject.getFinishDate())));
		 }
		lblProjectCode.setText(currentProject.getProjectCode());
		lblProjectName.setText(currentProject.getProjectName());
		lblStartDate.setText(CommonFuntion.convertToDate(new Date(currentProject.getStartDate())));
		lblFinishDate.setText(CommonFuntion.convertToDate(new Date(currentProject.getDueDate())));
		lblLocation.setText(currentProject.getLocation());
		lblInvestor.setText(currentProject.getInvestor());
		taDescription.setText(currentProject.getDescription());
	}
	private void getProjectInfo(String projectId) {
		projectService.getProjectById(projectId, new AsyncCallback<ProjectDTO>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Edit fail!");

			}

			@Override
			public void onSuccess(ProjectDTO result) {
				currentProject = result;
				displayProject();
			}

		});
		
	}

	@UiHandler("btnViewProjectPlan")
	void onBtnViewProjectPlanClick(ClickEvent event) {
		PMEntrypoint.get().callPop(currentProject.getProjectID());
		
	}
	@UiHandler("btnPMUpdateProjectStep2")
	void onBtnPMUpdateProjectStep2Click(ClickEvent event) {
		PMEntrypoint.get().PMUpdateProjectInfo(currentProject.getProjectID());
	}
	
	@UiHandler("btnSubCTList")
	void onBtnSubCTListClick(ClickEvent event) {
		PMEntrypoint.get().PMSubConstructorList(currentProject);
	}
	ProjectTaskDTO getFromlist(String taskId)
	{
		
		for(ProjectTaskDTO task:listTask)
		{
			if(task.getId().equals(taskId))
			{
				return task;
			}
			
		}
		return null;
	}
	void changeFilter()
	{
		ProjectTaskDTO parent = new ProjectTaskDTO();
		String ParentValue = cboParentTask.getValue(cboParentTask.getSelectedIndex());
		String taskType = cboTaskType.getValue(cboTaskType.getSelectedIndex());
		
		String subTask ="";
		if(!ParentValue.equals("-1")&&!ParentValue.equals("0"))
		{
			parent = getFromlist(ParentValue);
			if(parent.getSubTasks()!=null&&!parent.getSubTasks().equals(""))
			{
				subTask=parent.getSubTasks();
			}
		}
		
		List<ProjectTaskDTO> listData = new ArrayList<ProjectTaskDTO>();
		for(ProjectTaskDTO task :listTask)
		{
			Boolean searchCondition = true;
			if(taskType.equals("1"))
			{
				searchCondition=searchCondition&&(task.getParentId()==0);
			}
			if(taskType.equals("2"))
			{
				searchCondition=searchCondition&&(task.getIsMile()==1);
			}
			if(taskType.equals("3"))
			{
				searchCondition=searchCondition&&(task.getGroup()==1);
			}
			if(taskType.equals("4"))
			{
				searchCondition=searchCondition&&((task.getSubTasks().equals("")||task.getSubTasks()==null)&& task.getIsMile()==0);
			}
			if(searchCondition==false)
			{
				continue;
			}
			
if(cboParentTask.getValue(cboParentTask.getSelectedIndex()).equals("0"))
{
if(task.getParentId()!=0)
{
continue;	
}
}
if(!CommonFuntion.checkContain(subTask,""+task.getTaskId())&&!subTask.equals(""))
{
	continue;	
	}

				if (!cboStatus.getValue(cboStatus.getSelectedIndex()).equals("-1")) {
					int status = Integer.parseInt(cboStatus.getValue(cboStatus.getSelectedIndex()));
					if (task.getStatus() == status) {
						listData.add(task);
					}
				} else {
					listData.add(task);
				}
			//}
		}
		LoadDataForTable(listData);
	}
	
	@UiHandler("cboStatus")
	void onCboStatusChange(ChangeEvent event) {
		changeFilter();
		
	}

	@UiHandler("btnPJStaff")
	void onBtnPJStaffClick(ClickEvent event) {
		PMEntrypoint.get().PMProjectStaff(currentProject.getProjectID());
	}

	
	
	
	//chuyen trang thai project
	@UiHandler("button")
	void onButtonClick(ClickEvent event) {
		if(currentProject.getStatus()!=2&&currentProject.getStatus()!=3)
		{
		PMChangeProjectStatus dialog = new PMChangeProjectStatus(currentProject);
		dialog.setPopupPosition(500, 250);
		dialog.show();
		}
		else
		{
			Window.alert("Không thể thay đổi trạng thái của dự án đã hoàn thành hoặc dự án đã bị ngừng thực hiện");
		}
	}
	
	//tài liệu dự án
	@UiHandler("button_1")
	void onButton_1Click(ClickEvent event) {
		PMEntrypoint.get().ListDocuments(currentProject.getProjectID(), "1", currentProject.getProjectName(), "");
	}
	@UiHandler("cboParentTask")
	void onCboParentTaskChange(ChangeEvent event) {
		changeFilter();
	}
	@UiHandler("cboTaskType")
	void onCboTaskTypeChange(ChangeEvent event) {
		changeFilter();
	}
	@UiHandler("btnHmReq")
	void onBtnHmReqClick(ClickEvent event) {
		PMEntrypoint.get().PMHumanReq(currentProject);
	}
}
